package com.test.redis;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Least Recently Used
 * 最近很少使用，是一种常用的页面置换算法
 * 选择最近最久未使用的数据予以淘汰
 * lRU 的算法核心是哈希链表 HashMap+DoubleLinkedList，时间复杂度是O(1)
 *
 *
 * LinkedHashMap实现
 */
public class LRUDemo<K,V> extends LinkedHashMap<K,V> {

    private int capacity ; //缓存坑位

    public LRUDemo(int capacity) {
        //缓存坑位，负载因子，
        // accessOrder ：the ordering mode -
        //              <tt>true</tt> for access-order,访问顺序
        //              <tt>false</tt> for insertion-order 插入顺序
        super(capacity,0.75F,true);
        this.capacity = capacity;
    }

    /**
     *
     * 父类该方法默认返回false
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return super.size()>capacity;
    }

    public static void main(String[] args) {

        LRUDemo demo = new LRUDemo(3);
        demo.put(1,"a");
        demo.put(2,"b");
        demo.put(3,"c");
        System.out.println(demo.keySet());
        demo.put(4,"d");
        System.out.println(demo.keySet());
        demo.put(3,"c");
        System.out.println(demo.keySet());
        demo.put(3,"c");
        System.out.println(demo.keySet());
        demo.put(5,"c");
        System.out.println(demo.keySet());

      /*LinkedHashMap map = new LinkedHashMap(3);
        map.put(1,"a");
        map.put(2,"b");
        map.put(3,"c");
        System.out.println(map.keySet()); // [1, 2, 3]
        map.put(4,"d");
        System.out.println(map.keySet()); //[1, 2, 3, 4]
        */
    }
}
